package com.hzw.saas.web.hbox.security;

import cn.hutool.core.io.FileUtil;
import com.hzw.saas.common.security.token.MyDefaultAccessTokenConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 重写JWT转换器，使用公钥验证token准确性
 * @author sonam
 * @sine 2021/11/2 5:05 下午
 */
@Configuration
@RequiredArgsConstructor
public class WebShellSecurityConfig {

    public static final String PUBLIC_KEY_PATH = "saasr2-public.txt";

    @Bean
    @Primary
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    @Primary
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        String publicKey;
        try {
            publicKey = FileUtil.readString(new ClassPathResource(PUBLIC_KEY_PATH).getURL(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        converter.setVerifier(new RsaVerifier(publicKey));
        converter.setAccessTokenConverter(accessTokenConverter());
        return converter;
    }

    public AccessTokenConverter accessTokenConverter() {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        MyDefaultAccessTokenConverter userAuthenticationConverter = new MyDefaultAccessTokenConverter();
        accessTokenConverter.setUserTokenConverter(userAuthenticationConverter);
        return accessTokenConverter;
    }

}
